package com.base.cn.platform.os.interceptor;

import com.base.cn.platform.os.common.constants.CommonConstants;
import com.base.cn.platform.os.common.j2cache.CustomCacheChannel;
import com.base.cn.platform.os.common.j2cache.J2CacheRegion;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.common.utils.result.ResultUtil;
import com.base.cn.platform.os.common.utils.web.WebMobileLoginUtil;
import com.base.cn.platform.os.common.utils.web.WebUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 前台用户登录拦截
 *
 * @author s.li
 * @create 2018-05-30-9:18
 */
@Slf4j
public class WebUserLoginInterceptor implements HandlerInterceptor {

    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();

    @Autowired
    private WebMobileLoginUtil webMobileLoginUtil;
    @Autowired
    private CustomCacheChannel customCacheChannel;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求类型
        JsonObject user = webMobileLoginUtil.getLoginUser(request);
        if(user==null){
            notLoginRedirect(request,response);
            return false;
        }else{
            String sid = WebUtils.getCookie(request,CommonConstants.USER_SINGLE_ID);
            String userId = user.get("id").getAsString();
            String token = (String)customCacheChannel.get(J2CacheRegion.THIRTY_DAY_REGION.getKey(),userId).getValue();
            if(StringUtils.isEmpty(token) || StringUtils.isEmpty(sid) || !sid.equals(token)){
                if(StringUtils.isNotEmpty(sid)){
                    customCacheChannel.evict(J2CacheRegion.ONE_DAY_REGION.getKey(),sid);
                    customCacheChannel.evict(J2CacheRegion.THIRTY_DAY_REGION.getKey(),sid);
                }
                notLoginRedirect(request,response);
                return false;
            }
            return true;
        }
    }

    /**
     * 未登录跳转
     * @param request
     * @param response
     * @throws Exception
     */
    private void notLoginRedirect(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String accept = request.getHeader("accept");
        String requestURL = WebUtils.getCompleteUrl(request);
        String contentType = request.getHeader("content-type");
        if(WebUtils.isAjaxRequest(request) && accept.toLowerCase().contains("json")){
            requestURL = request.getHeader("referer");
        }
        if(StringUtils.isNotEmpty(requestURL)){
            WebUtils.setCookie(response, CommonConstants.REDIRECT,requestURL,1);
        }
        if(WebUtils.isAjaxRequest(request) && accept.toLowerCase().contains("json")){
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(gson.toJson(ResultUtil.ERROR("登录过期，请重新登录")));
        }else{
            if(contentType!=null && contentType.contains("json")){//是ajax请求，但返回的不是json
                response.sendRedirect("/web/user/autoToLoginPage");
            }else{
                response.sendRedirect("/web/user/login");
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
